package com.yoyo.yyadsdk.activity;

import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.anye.greendao.gen.AppEntityDao;
import com.anye.greendao.gen.LocalPullEntityDao;
import com.yoyo.ad.utils.StringUtil;
import com.yoyo.yyadsdk.bean.dao.AppEntity;
import com.yoyo.yyadsdk.bean.dao.LocalPullEntity;
import com.yoyo.yyadsdk.bean.dao.PullEntity;
import com.yoyo.yyadsdk.config.PullFeature;
import com.yoyo.yyadsdk.serv.DownLoadAPKService;
import com.yoyo.yyadsdk.util.ActivityUtils;
import com.yoyo.yyadsdk.util.AlarmUtils;
import com.yoyo.yyadsdk.util.GreenDaoManager;
import com.yoyo.yyadsdk.util.TimeUtils;

import java.util.ArrayList;
import java.util.List;

public class EmptyActivity extends AppCompatActivity {
    private static final String TAG = "EmptyActivity";
    public static String ACTION = "action";
    public static String PULL_TYPE = "pullType";
    public static String PULL_ENTITY = "pullEntity";
    public static String TOP_PACKAGE_NAME = "topPackageName";
    private String pkgName;
    private String name;

    public static void launch(Context context, @PullFeature.PullTypeFlags int pullType, @Nullable PullEntity pullEntity) {
        if (context != null && pullEntity != null) {
            ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
            String pkgName = activityManager.getRunningTasks(1).get(0).topActivity.getPackageName();
            context.startActivity(new Intent(context, EmptyActivity.class)
                    .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                    .putExtra(EmptyActivity.PULL_TYPE, pullType)
                    .putExtra(EmptyActivity.TOP_PACKAGE_NAME, pkgName)
                    .putExtra(EmptyActivity.PULL_ENTITY, pullEntity));
        }
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        pkgName = getIntent().getStringExtra(EmptyActivity.TOP_PACKAGE_NAME);
        int pullType = getIntent().getIntExtra(PULL_TYPE, PullFeature.PULL_UN_KNOW);
        PullEntity pullEntity = getIntent().getParcelableExtra(PULL_ENTITY);
        String packageName = pullEntity.getTPkg();
        boolean isBackHome = pullEntity.getIsBackHome() == 1;
        String action = pullEntity.getAction();
        boolean allowDiscover = pullEntity.getAllowDiscover() == 1;

        if (ActivityUtils.isAppInstalled(this, packageName)) {
            if (action != null && !action.isEmpty()) {
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_VIEW);
                intent.setData(Uri.parse(action));
                intent.putExtra(EmptyActivity.PULL_TYPE, pullType)
                        .putExtra(EmptyActivity.ACTION, action);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                if (!allowDiscover)
                    intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
                startActivity(intent);
            } else {
                Intent intent = getAppOpenIntentByPackageName(EmptyActivity.this, packageName);
                if (intent == null) {
                    installApp(packageName);
                } else {
                    intent.putExtra(EmptyActivity.PULL_TYPE, pullType).putExtra(EmptyActivity.ACTION, action);
                    if (!allowDiscover)
                        intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
                    startActivity(intent);
                }
            }
            //记录拉活信息到本地
            LocalPullEntityDao localPullEntityDao = GreenDaoManager.getInstance().getDaoSession().getLocalPullEntityDao();
            LocalPullEntity localPullEntity = new LocalPullEntity();
            localPullEntity.setAction(pullEntity.getAction());
            localPullEntity.setTPkg(pullEntity.getTPkg());
            localPullEntity.setType(pullEntity.getType());
            localPullEntity.setPullTime(System.currentTimeMillis());
            localPullEntityDao.insertOrReplace(localPullEntity);
            pullEntity.setPullTimes(pullEntity.getPullTimes() + 1);
            GreenDaoManager.getInstance().getDaoSession().getPullEntityDao().insertOrReplace(pullEntity);
        } else {
            installApp(packageName);
        }
        AppEntityDao appEntityDao = GreenDaoManager.getInstance().getDaoSession().getAppEntityDao();
        List<AppEntity> list = appEntityDao.queryBuilder().where(AppEntityDao.Properties.TPkg.eq(packageName)).list();
        if (list != null && list.size() > 0 && list.get(0).getLiveTime() > 0) {
            AppEntity appEntity = list.get(0);
            AlarmUtils.addTask(PullFeature.ALARM_MONITOR_TIME_ALIVE, packageName, appEntity.getLiveTime() * TimeUtils.SECOND, false, 0);
        }

        if (isBackHome) {
//            ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
//            String className = activityManager.getRunningTasks(1).get(0).topActivity.getClassName();
//            final String pkgName = activityManager.getRunningTasks(1).get(0).topActivity.getPackageName();
            if (pkgName.equalsIgnoreCase(packageName)) {
                finish();
                return;
            }
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    Intent intentHome;
                    getHomePackageName(EmptyActivity.this);
                    String uri = "com.android.launcher3";
                    String uriStr = StringUtil.isNull(name) ? uri : name;
                    if (pkgName.contains(uriStr)) {
                        intentHome = new Intent(Intent.ACTION_MAIN);
                        intentHome.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        intentHome.addCategory(Intent.CATEGORY_HOME);
                    } else {
                        intentHome = getAppOpenIntentByPackageName(EmptyActivity.this, pkgName);
                    }
                    startActivity(intentHome);
                    finish();
                }
            }, 100);
        } else {
            finish();
        }
    }

    private void installApp(String tPkg) {
        List<AppEntity> list = GreenDaoManager.getInstance().getDaoSession().getAppEntityDao().queryBuilder().where(AppEntityDao.Properties.TPkg.eq(tPkg)).list();
        if (list != null && list.size() > 0 && list.get(0).getIsAutoInst() == 1) {
            startService(new Intent(EmptyActivity.this, DownLoadAPKService.class)
                    .putExtra(DownLoadAPKService.PARAM_APK_URL, list.get(0).getAppUrl())
                    .putExtra(DownLoadAPKService.PARAM_APK_PACKAGE_NAME, list.get(0).getTPkg()));
        }
    }

    /**
     * 启动第三方apk
     * <p>
     * 如果已经启动apk，则直接将apk从后台调到前台运行（类似home键之后再点击apk图标启动），如果未启动apk，则重新启动
     */

    public static Intent getAppOpenIntentByPackageName(Context context, String packageName) {
        String mainAct = null;
        PackageManager pkgMag = context.getPackageManager();
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);
        intent.setFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED | Intent.FLAG_ACTIVITY_NEW_TASK);
        @SuppressLint("WrongConstant")
        List<ResolveInfo> list = pkgMag.queryIntentActivities(intent, PackageManager.GET_ACTIVITIES);
        // 获取指定应用程序activity的信息(按我的理解是：某一个应用程序的最后一个在前台出现过的activity。)
        //        ResolveInfo resolveInfo = pkgMag.resolveActivity(intent, 0);
        for (int i = 0; i < list.size(); i++) {
            ResolveInfo info = list.get(i);
            if (info.activityInfo.packageName.equals(packageName)) {
                mainAct = info.activityInfo.name;
                break;
            }
        }
        if (TextUtils.isEmpty(mainAct)) {
            return null;
        }
        intent.setComponent(new ComponentName(packageName, mainAct));
        return intent;
    }

    private void getHomePackageName(Context context) {
        if (name == null) {
            PackageManager packageManager = context.getPackageManager();
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_HOME);
            List<ResolveInfo> resolveInfo = packageManager.queryIntentActivities(intent,
                    PackageManager.MATCH_DEFAULT_ONLY);
            for (ResolveInfo ri : resolveInfo) {
                if (ri.activityInfo.packageName.contains("launcher")) {
                    name = ri.activityInfo.packageName;
                }
            }
        }
    }
}
